package store

import (
	"context"
	"hotgo/api/api/storeorder"
	"hotgo/internal/dao"
	"hotgo/internal/library/payment"
	"hotgo/internal/model/input/payin"
	"hotgo/internal/service"

	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

var (
	StoreOrder = cStoreOrder{}
)

type cStoreOrder struct {
}

// 创建订单
func (c *cStoreOrder) Create(ctx context.Context, in *storeorder.CreateReq) (res *storeorder.CreateRes, err error) {
	res = new(storeorder.CreateRes)
	//用户信息
	userRecord, _ := dao.EpMember.Ctx(ctx).Where(dao.EpMember.Columns().Id, in.UserId).One()
	if userRecord.IsEmpty() {
		err = gerror.New("用户不存在")
		return
	}
	//收货地址
	addressRecord, _ := dao.EpMemberAddress.Ctx(ctx).Where(dao.EpMemberAddress.Columns().Id, in.AddressId).One()
	if addressRecord.IsEmpty() {
		err = gerror.New("收货地址不存在")
		return
	}
	//购物车列表
	cartRecords, _ := dao.StoreCart.Ctx(ctx).WhereIn(dao.StoreCart.Columns().Id, in.CartIds).All()
	orderData := g.Map{
		"uid":            in.UserId,
		"nickname":       userRecord["nickname"],
		"order_no":       payment.GenOutTradeNo(),
		"total_fee":      0,
		"real_fee":       0,
		"remark":         in.Remark,
		"address":        addressRecord["address"],
		"name":           addressRecord["name"],
		"mobile":         addressRecord["mobile"],
		"address_code":   gconv.String(addressRecord["province_code"]) + "/" + gconv.String(addressRecord["city_code"]) + "/" + gconv.String(addressRecord["county_code"]),
		"address_name":   gconv.String(addressRecord["province"]) + "/" + gconv.String(addressRecord["city"]) + "/" + gconv.String(addressRecord["county"]),
		"status":         0,
		"user_coupon_id": in.UserCouponId,
	}
	orderResult, _ := dao.StoreOrder.Ctx(ctx).Data(orderData).Insert()
	orderId, _ := orderResult.LastInsertId()
	orderData["id"] = orderId
	totalFee := 0
	couponFee := 0
	subject := garray.NewStrArray()
	if cartRecords.Len() == 0 {
		//查询商品
		productRecord, _ := dao.StoreProduct.Ctx(ctx).Where(dao.StoreProduct.Columns().Id, in.ProductId).One()
		if productRecord.IsEmpty() {
			err = gerror.New("商品不存在")
			return
		}
		subject.Append(gconv.String(productRecord["title"]))
		//商品规格
		skuRecord, _ := dao.StoreProductSku.Ctx(ctx).Where(dao.StoreProductSku.Columns().Id, in.ProductSkuId).One()
		productSkuRecord := g.Map{
			"id":    0,
			"name":  "默认规格",
			"price": productRecord["price"],
		}
		if !skuRecord.IsEmpty() {
			productSkuRecord = skuRecord.Map()
		}
		orderDetailData := g.Map{
			"order_id":         orderId,
			"order_no":         orderData["order_no"],
			"order_detail_no":  payment.GenOrderSn(),
			"product_id":       productRecord["id"],
			"product_sku_id":   productSkuRecord["id"],
			"product_sku_name": productSkuRecord["name"],
			"product_name":     productRecord["title"],
			"product_image":    productRecord["image"],
			"product_code":     productRecord["code"],
			"amount":           in.Num,
			"price":            productSkuRecord["price"],
		}
		dao.StoreOrderDetail.Ctx(ctx).Data(orderDetailData).Insert()
		totalFee = gconv.Int(productSkuRecord["price"]) * int(in.Num)
	} else {
		for _, v := range cartRecords {
			//查询商品
			productRecord, _ := dao.StoreProduct.Ctx(ctx).Where(dao.StoreProduct.Columns().Id, v["product_id"]).One()
			if productRecord.IsEmpty() {
				continue
			}
			subject.Append(gconv.String(productRecord["title"]))
			//商品规格
			skuRecord, _ := dao.StoreProductSku.Ctx(ctx).Where(dao.StoreProductSku.Columns().Id, v["product_sku_id"]).One()
			productSkuRecord := g.Map{
				"id":    0,
				"name":  "默认规格",
				"price": productRecord["price"],
			}
			if !skuRecord.IsEmpty() {
				productSkuRecord = skuRecord.Map()
			}
			orderDetailData := g.Map{
				"order_id":         orderId,
				"order_no":         orderData["order_no"],
				"order_detail_no":  payment.GenOrderSn(),
				"product_id":       productRecord["id"],
				"product_sku_id":   productSkuRecord["id"],
				"product_sku_name": productSkuRecord["name"],
				"product_name":     productRecord["title"],
				"product_image":    productRecord["image"],
				"product_code":     productRecord["code"],
				"amount":           v["amount"],
				"price":            productSkuRecord["price"],
			}
			dao.StoreOrderDetail.Ctx(ctx).Data(orderDetailData).Insert()
			totalFee += gconv.Int(productSkuRecord["price"]) * int(in.Num)
		}
	}
	orderData["total_fee"] = totalFee
	orderData["real_fee"] = totalFee - couponFee
	dao.StoreOrder.Ctx(ctx).Where(dao.StoreOrder.Columns().Id, orderId).Data(orderData).Update()
	res.OrderInfo = orderData

	openId := ""
	userOauthRecords, _ := dao.EpMemberOauth.Ctx(ctx).Where(dao.EpMemberOauth.Columns().MemberId, in.UserId).All()
	for _, v := range userOauthRecords {
		if gconv.String(v["oauth_client"]) == in.Platform {
			openId = gconv.String(v["oauth_openid"])
			break
		}
	}
	// 创建第三方平台支付订单
	payInput := payin.PayCreateInp{
		Subject:    subject.Join(","),
		Detail:     gjson.New(orderData),
		OrderGroup: "store",
		OrderSn:    gconv.String(orderData["order_no"]),
		PayAmount:  gconv.Float64(orderData["real_fee"]),
		PayType:    in.PayType,
		ReturnUrl:  "",
		TradeType:  "mini",
		Openid:     openId,
	}
	payInfo, err := service.Pay().Create(ctx, payInput)
	if err != nil {
		err = gerror.New(err.Error())
		return
	}
	res.PayParams = payInfo.Order
	return
}
